﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FileExplorer_TreeView;
using System.Configuration;
using System.Collections.Specialized;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        FileExplorer fe = new FileExplorer();
        
        string UserFolder = "";
        public Form1()
        {
            InitializeComponent();
        }

        private void trwFileExplorer_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if (e.Node.Nodes[0].Text == "")
            {
                TreeNode node = fe.EnumerateDirectory(e.Node);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.treeView1.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(trwFileExplorer_BeforeExpand);
            this.Load += new System.EventHandler(this.Form1_Load);
            //create a list based on the class CostCenter and add items
            BindingList<CostCenter> list = new BindingList<CostCenter>();
            list.Add(new CostCenter("Retaining Walls", "090"));
            list.Add(new CostCenter("Concrete Pump", "285"));
            list.Add(new CostCenter("Concretor", "300"));
            list.Add(new CostCenter("Back Blade Slab", "315"));
            list.Add(new CostCenter("Crane Hire", "345"));
            list.Add(new CostCenter("Carpenter – Frame & Truss", "360"));
            list.Add(new CostCenter("Carpenter- Ext Cladding & Eaves", "470"));
            list.Add(new CostCenter("Brick Labour", "520"));
            list.Add(new CostCenter("Brick Clean", "525"));
            list.Add(new CostCenter("Carpenter Internal Fix", "580"));
            list.Add(new CostCenter("Painter", "655"));
            list.Add(new CostCenter("Carpenter External Labour", "700"));
            list.Add(new CostCenter("Carpenter Final Fix", "755"));
            list.Add(new CostCenter("Floor Sanding", "770"));
            list.Add(new CostCenter("Driveway Preparation", "775"));
            list.Add(new CostCenter("Driveway Fill", "785"));
            list.Add(new CostCenter("External Concrete Labour", "810"));
            list.Add(new CostCenter("Fencing", "820"));
            list.Add(new CostCenter("Site Clean", "860"));
            list.Add(new CostCenter("Landscape", "890"));
            list.Add(new CostCenter("Landscape Maintenance", "891"));

            //set the checkboxlist's datasource
            chkCostCenterList.DataSource = list;
            chkCostCenterList.DisplayMember = "Name";
            chkCostCenterList.ValueMember = "Number";

            for (int i = 0; i < chkCostCenterList.Items.Count; i++)
                chkCostCenterList.SetItemChecked(i, true);

            fe.CreateTree(this.treeView1);
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void AddFolders_Button_Click(object sender, EventArgs e)
        {
            Folders_List.Items.Clear();
            foreach (TreeNode node in treeView1.Nodes)
            {
                GetNodeRecursive(node);
            }
        }

        private void GetNodeRecursive(TreeNode treeNode)
        {
            if (treeNode.Checked == true)
            {
                string JobNumber = Prompt.ShowDialog("Job Number for " + Environment.NewLine + treeNode.FullPath.Replace(@"\\", @"\"), "");
                if (JobNumber != String.Empty)
                {
                    Item obj = new Item();
                    obj.strText = treeNode.FullPath.Replace(@"\\", @"\");
                    obj.strValue = JobNumber.Trim();

                    Item obj2 = new Item();
                    obj2.strText = "Job number: " + JobNumber.Trim();
                    obj2.strValue = "";

                    Folders_List.Items.Add(obj);
                    Folders_List.Items.Add(obj2);
                }
            }
            foreach (TreeNode tn in treeNode.Nodes)
            {
                GetNodeRecursive(tn);
            }

        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Create_Button2_Click(object sender, EventArgs e)
        {
            CopyFiles(false);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CopyFiles(true);
        }

        private void CopyFiles(bool IsUpdate)
        {
            //string sourceDir = @"P:\DATABUILD\Docs\Jobs";
            string sourceDir = @"C:\Test";
            string supervisorDir = "Site Supervisor Share";
            bool copyFlag = false;
            if (Folders_List.Items.Count == 0)
            {
                MessageBox.Show("You have to select at least one folder");
                return;
            }
            if (chkCostCenterList.CheckedItems.Count == 0)
            {
                MessageBox.Show("You have to select at least one purchase order type");
                return;
            }

            foreach (Item obj in Folders_List.Items)
            {
                if (obj.strValue != "")
                {
                    string sourcePath = Path.Combine(sourceDir, obj.strValue);
                    string destPath = Path.Combine(obj.strText, supervisorDir);
                    //create supervisor folder in root folder
                    if (!Directory.Exists(destPath))
                        Directory.CreateDirectory(destPath);

                    //if update, clean destination folder
                    if (IsUpdate)
                    {
                        foreach (var file in Directory.GetFiles(destPath))
                        {
                            File.Delete(file);
                        }
                    }

                    object[] items = chkCostCenterList.CheckedItems.OfType<CostCenter>().ToArray();
                    //copy purchase orders (version 1)
                    string pattern = "";
                    if (Directory.Exists(sourcePath))
                    {
                        foreach (CostCenter costcenter in items)
                        {
                            pattern = String.Concat(obj.strValue, "_", costcenter.Number);
                            foreach (var file in Directory.GetFiles(sourcePath))
                            {
                                if (Path.GetFileName(file).Contains(pattern))
                                {
                                    copyFlag = true;
                                    File.Copy(file, Path.Combine(destPath, Path.GetFileName(file)), true);
                                }
                            }
                        }
                    }
                    else
                    {
                        //source dir + jobnumber does not exist
                    }

                    //copy other documents (version 2)
                    string[] appSettings = ConfigurationSettings.AppSettings.AllKeys;
                    if (appSettings.Length > 0)
                    {
                        if (!Directory.Exists(destPath))
                            Directory.CreateDirectory(destPath);

                        foreach (string setting in appSettings)
                        {
                            string directory = ConfigurationSettings.AppSettings[setting].Split('/')[1];
                            string file = ConfigurationSettings.AppSettings[setting].Split('/')[2];
                            foreach (var fileFromPath in Directory.GetFiles(Path.Combine(obj.strText, directory)))
                            {
                                if (Path.GetFileName(fileFromPath).ToLower().Replace(" ", "").Contains(file.ToLower().Replace(" ", "")))
                                {
                                    File.Copy(fileFromPath, Path.Combine(destPath, Path.GetFileName(fileFromPath)), true);
                                }
                            }
                        }
                    }
                }
            }

            if (copyFlag)
                MessageBox.Show("All files copied");
            else
                MessageBox.Show("No file copied");

        }

        private void ClearFolders_Button_Click(object sender, EventArgs e)
        {
            Folders_List.Items.Clear();
        }
    }
	
	public class CostCenter
    {
        private string name;
        private string number;
        public CostCenter() { }
        public CostCenter(string _name, string _number)
        {
            Name = _name;
            Number = _number;
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Number
        {
            get { return number; }
            set { number = value; }
        }
    }

    public static class Prompt
    {
        public static string ShowDialog(string text, string caption)
        {
            Form prompt = new Form();
            prompt.Width = 500;
            prompt.Height = 150;
            prompt.Text = caption;
            prompt.StartPosition = FormStartPosition.CenterScreen;
            Label textLabel = new Label() { Left = 50, Top = 20, Text = text };
            TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 };
            Button confirmation = new Button() { Text = "OK", Left = 350, Width = 100, Top = 70 };
            textLabel.AutoSize = true;
            confirmation.Click += (sender, e) => { prompt.Close(); };
            prompt.Controls.Add(textBox);
            prompt.Controls.Add(confirmation);
            prompt.Controls.Add(textLabel);
            prompt.AcceptButton = confirmation;
            prompt.ShowDialog();
            return textBox.Text;
        }
    }

    public class Item
    {
        public string strText;
        public string strValue;
        public override string ToString()
        {
            return this.strText;
        }
    }
}
